package testGroovy


import static groovyx.net.http.ContentType.BINARY
import static groovyx.net.http.ContentType.URLENC

import java.net.InetAddress;

import groovyx.net.http.HttpResponseException
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

import org.cyberneko.html.parsers.SAXParser

class TestRandomIPAccess {

	private static final _URL_PROPOSAL = 'ebusiness/auto/newness/index.do'
	static main(args) {
		10.times {
			try {
				RESTClient client = new RESTClient('http://www.pingan.com/').with {
					client.params.setParameter(
							org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY ,
							randomProxy()
//							new org.apache.http.HttpHost(ipList[randomIndex], 8888 )
							)
					it
				}
				def params = [
					requestContentType  : URLENC,
					contentType         : BINARY,
					path                : _URL_PROPOSAL,
					query 				: [
						cityCode		:110100,
						provinceCode	:110000
					]
				]

				def title = client.get params, { resp, stream ->
					def file = "E:/content${Math.random()}.html" as File
					file.withOutputStream { os -> os << stream }
					def dom = htmlParser.parse(file).depthFirst()
					dom.TITLE.text()
				}
				println title
			} catch(ex) {
								println ex
//				ex.printStackTrace()
			}
		}
	}

	def static randomProxy() {
		def availableIp = null
		def flag = false
		def ipAndPortList = getProxyMap()
		ipAndPortList.findResult { ip, port ->
			def address = InetAddress.getByName(ip);
			def availableFlag = address.isReachable(5000)
			if(availableFlag) {
				println "[${ip}:${port}]可用"
				availableIp = [ip, port]
			} else {
				println "[${ip}:${port}]不可用"
				availableIp = null
			}
		}
		//		def randomIndex = ((int)Math.round(Math.random() * availableIpList.size()))-1
		createProxy(availableIp[0], availableIp[1])
	}

	def static createProxy(ip,port) {
		new org.apache.http.HttpHost(ip, port)
	}

	def static getProxyMap() {
		def file = 'src/main/resources/proxy.txt' as File
		def map = [:]
		file.eachLine { line ->
			def ipAndPort = line.split('#')
			map.putAt(ipAndPort[0],ipAndPort[1]);
		}
		map.collect { entry ->
			[entry.key, entry.value]
		}
	}

	def static getHtmlParser(){
		def nekoParser = new SAXParser().with {
			it.setFeature 'http://xml.org/sax/features/namespaces', false
			it
		}
		new XmlParser(nekoParser)
	}
}
